/**
 * Created by IntelliJ IDEA.
 * User: evgeniysorokin
 * Date: 20.09.12
 */
public class PercolationStats {
    private double[] results;

    public PercolationStats(int N, int T) {
        Percolation p = new Percolation(N);
        
        results = new double[T];
        
        int openSites;
        int sites = N * N;
        double result;
                
        for (int n = 0; n < T; n++) {
            
            openSites = 0;

            while (!p.percolates()) {
                try {
                    int i = StdRandom.uniform(1, N + 1), j = StdRandom.uniform(1, N + 1);
                    if(!p.isOpen(i, j)) {
                        p.open(i, j);
                        openSites++;
                    }
                } catch (IndexOutOfBoundsException e) {
                    System.out.println("outOfBound");
                }
            }

            p = new Percolation(N);

            result = (double)openSites / (double)sites;

            results[n] = result;
        }
        
    }

    public double mean() {
        return StdStats.mean(results);
    }

    public double stddev() {
        return StdStats.stddev(results);
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]), T = Integer.parseInt(args[1]);

        Stopwatch stopwatch = new Stopwatch();

        PercolationStats ps = new PercolationStats(N, T);

        System.out.println("elapsed time: " + stopwatch.elapsedTime());

        double mean = ps.mean(), stddev = ps.stddev();
        
        System.out.println("mean = " + mean);
        System.out.println("stddev = " + stddev);

        System.out.println("95% confidence interval = " + (mean - (1.96 * stddev) / Math.sqrt((double) T)) + ", " + (mean + (1.96 * stddev) / Math.sqrt((double) T)));
    }

}
